package controllers;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import services.AdministratorService;
import services.ChallengeService;
import services.EventService;
import domain.Administrator;
import domain.Challenge;
import domain.Event;

@Controller
@RequestMapping("/challenge")
public class ChallengeController extends AbstractController {

	// Constructors -----------------------------------------------------------

	public ChallengeController() {
		super();
	}

	// Services ---------------------------------------------------------------

	@Autowired
	private ChallengeService challengeService;

	@Autowired
	private EventService eventService;
	
	@Autowired
	private AdministratorService administratorService;

	// List events ------------------------------------------------------------

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView list(@RequestParam int eventId) {
		ModelAndView result;
		Collection<Challenge> challenges;
		boolean showDetails=false;
		Administrator a;
		Event e = eventService.findOne(eventId);
		challenges = challengeService.findChallengesByEvent(e);
		result = new ModelAndView("challenge/list");
		result.addObject("requestURI", "challenge/list.do");
		result.addObject("challenges", challenges);
		try{
			a = administratorService.findByPrincipal();
		}
		catch(Exception ex){
			a=null;
		}
		
		if(a!=null&&a==e.getAdministrator())
		{
			showDetails=true;
		}
		result.addObject("showDetails", showDetails);
		result.addObject("eventId", e.getId());
		
		if (e.getStartMoment().compareTo(new Date()) > 0){
			result.addObject("active",true);
		}
		
		return result;
		
		
	}

}
